// send.h
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WebSocketsClient.h>
#include <initializer_list>
#include <utility>

// 由 main.ino 定义
extern WebSocketsClient webSocket;
extern String WS_TARGET_ID;      // presence/connected 时绑定

template <typename TDoc>
static inline bool _wsSend(const TDoc& doc) {
  String json; serializeJson(doc, json);
  Serial.println("发送消息: " + json);
  return webSocket.sendTXT(json);
}

// 发送私聊（服务器会在下行加 from/fromName）
static inline bool sendPrivateToId(const String& toId, const String& content) {
  if (!toId.length()) { Serial.println("[warn] 目标ID为空, 未发送"); return false; }
  StaticJsonDocument<384> doc;
  doc["type"]    = "servo_control";
  doc["to"]      = toId;      // 一定是“id”
  doc["content"] = content;   // 业务数据放这里
  return _wsSend(doc);
}

// 把 [{"c":0,"p":xxx},...] 序列化成字符串作为私聊的 content 发给目标
static inline bool sendServoControl(std::initializer_list<std::pair<int,int>> items) {
  StaticJsonDocument<256> arrDoc;
  JsonArray arr = arrDoc.to<JsonArray>();
  for (auto& it : items) {
    JsonObject o = arr.createNestedObject();
    o["c"] = it.first;
    o["p"] = it.second;
  }
  String content; serializeJson(arrDoc, content);
  return sendPrivateToId(WS_TARGET_ID, content);
}

// // readFirst3AndSendServos()
/* ===== 新增：直接发送 type="servo_control" 供 server-c 解析 ===== */
static inline bool sendServoControlAsServerControl(std::initializer_list<std::pair<int,int>> items) {
  // 先把 {c,p} 列表序列化成 JSON 数组字符串
  StaticJsonDocument<256> arrDoc;
  JsonArray arr = arrDoc.to<JsonArray>();
  for (auto& it : items) {
    JsonObject o = arr.createNestedObject();
    o["c"] = it.first;
    o["p"] = it.second;
  }
  String content; serializeJson(arrDoc, content);

  // 按 server-c 要求发：type = "servo_control", content = 上面的字符串
  StaticJsonDocument<320> doc;
  doc["type"]    = "servo_control";
  doc["content"] = content;
  return _wsSend(doc);
}

